package czk.concrent.reentrantLock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/5/31 16:28
 */
// 可打断锁
public class Test2 {
    private static ReentrantLock lock=new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        // 新线程，获取可打断锁
        Thread t1=new Thread(()->{
            // 获取可打断锁
            try {
                // 获得的锁是可打断的
                System.out.println("分线程去获取锁");
                lock.lockInterruptibly();
                System.out.println("获取到了锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("没有获得锁，返回");
                return;
            }
            try {

            } finally {
                // 释放锁
                System.out.println("释放锁");
                lock.unlock();
            }
        },"t1");
        // 主线程获取锁，此时t1获取不到锁，去等待
        System.out.println("主线程去获取锁");
        lock.lock();
        t1.start();
        // 线程休息
        Thread.sleep(2*1000);
        try {
            // 去打断
            t1.interrupt();
        }finally {
            lock.unlock();
        }

    }
}
